import React, { Component } from 'react';
import { Tabs, Button, Table, Divider, Modal, Form, Input, Icon, Switch, notification, Select, Drawer, Row, Col, DatePicker, Radio } from 'antd';
import '@/assets/css/settings';
import * as APIService from '../../axios/api';
import moment from 'moment';
import 'moment/locale/zh-cn';
import locale from 'antd/es/date-picker/locale/zh_CN';
import 'moment/locale/zh-cn';
//moment.locale('zh-cn');
const { TabPane } = Tabs;
const { Option } = Select;
const { confirm } = Modal;
const FormItem = Form.Item;
//弹出通知提醒框
function openNotification(type, message) {
	notification.open({
		type: type,
		message: message,
		duration: 2,
	});
};

const dateFormat = 'YYYY-MM-DD HH:mm:ss';
class App extends Component {
	state = {
		dataSource: [],
		pagination: {
			current: 1,   //当前页
			pageSize: 10,   //每一页的条数
		},
		loading: false,
		visible: false,
		modalData: '',//选中的数据
		handleType: 0,// 修改1
		options: [],
		typeData: [],
		taskType: 0, //显示执行一次
		startTime: moment().startOf('day').format('YYYY-MM-DD HH:mm:ss'),
		endTime: '',
		time: moment().startOf('day').format('YYYY-MM-DD HH:mm:ss'),
		visible_planType: '0',
		columns: [
			{
				dataIndex: '',
				width: '80px',

			},
			{
				title: '序号',
				width: '10%',
				//dataIndex: 'id',
				render: (text, record, index) => {
					return (
						`${(this.state.pagination.current - 1) * (this.state.pagination.pageSize) + (index + 1)}`
					)
				}
			},
			{
				title: '编码',
				dataIndex: 'jobCod',
			},

			{
				title: '周期计划名称',
				dataIndex: 'name',
			},

			{
				title: '周期计划分组',
				dataIndex: 'groupName',
			},

			{
				title: '周期计划类型',
				dataIndex: 'taskType',
			},

			{
				title: '是否启用',
				render: () => {
					return <span>
						<Switch checkedChildren="开" unCheckedChildren="关" defaultChecked />
					</span>
				}
			},

			{
				title: '操作',
				width: '12%',
				render: (text, record) => {
					return <span>
						<a onClick={() => this.showModal(record, 1)}>修改</a>
						<Divider type="vertical" />
						<a onClick={() => this.deleteJob(record, 2)}>
							删除
			</a>
					</span>
				}
			}
		]
	}

	componentDidMount() {
		this.fetch('');
	}

	componentWillUnmount() {
		this.setState = () => {
			return;
		};
	}


	//分页查询
	fetch = (str) => {
		this.setState({ loading: true });
		APIService.findJobList(str).then(data => {
			const dataSource = data.data.data;

			this.setState({
				dataSource: dataSource,
				loading: false
			})
			const pagination = { ...this.state.pagination };
			pagination.total = data.data.data.total;
			pagination.showSizeChanger = true;
			pagination.onShowSizeChange = (current, pageSize) => {
				const pagination = { ...this.state.pagination };
				pagination.pageSize = pageSize;
				pagination.current = current;
				this.setState({ pagination });
				const str = 'pageNum=' + current + '&pageSize=' + pageSize
				this.fetch(str)
			}
			pagination.showQuickJumper = false;
			pagination.onChange = (current, pageSize) => {
				const pagination = { ...this.state.pagination };
				pagination.pageSize = pageSize;
				pagination.current = current;
				this.setState({ pagination });
				const str = 'pageNum=' + current + '&pageSize=' + pageSize
				console.log(str)
				this.fetch(str)
			}
			pagination.showTotal = total => `共 ${total} 条数据`
			this.setState({
				dataSource: dataSource,
				loading: false,
				pagination
			})
		})

		//查询
		const that = this;
		APIService.findJobClassList().then(data => {
			const dataSource = data.data.data;
			that.setState({
				typeData: dataSource
			})
		})
	}

	handleChangeTab = key => { }

	//添加 修改
	submitAdd = (e) => {
		
		let arr = []
		if (this.state.taskType === 0) {
			arr = ['groupName', 'className', 'methodName', 'taskType', 'explain', 'name', 'jobCod', 'rate', 'time', 'typeData'];
		} else {
			arr = ['groupName', 'className', 'methodName', 'taskType', 'explain', 'name', 'jobCod', 'rate', 'startTime', 'endTime', 'typeData'];
		}
		this.props.form.validateFields(arr, (err, values) => {
			if (!err) {
				if (values.startTime) {
					values.startTime = moment(values.startTime).format(dateFormat);
				}
				if (values.endTime) {
					values.endTime = moment(values.endTime).format(dateFormat);
				}
				if (values.time) {
					values.time = moment(values.time).format(dateFormat);
				}


				let typeData = this.state.typeData[0];

				var json = { id: this.state.id, jobCod: values.jobCod, name: values.name, time: values.time, taskType: parseInt(values.taskType), explain: values.explain, methodName: typeData.methodName, groupName: typeData.groupName, className: typeData.className, dateName: values.dateName }

				//执行一次 基础循环条件判断
				let choose = (jiek) => {
					if (this.state.taskType === 0) {
						json = Object.assign({}, json, { time: values.time })
						jiek(json).then(data => {
							if (data.data.code === 200) {
								openNotification('success', '操作成功')
							} else {
								openNotification('warning', data.data.msg)
							}
							const that = this;
							that.handleCancel();
							that.props.form.resetFields();
							that.setState({
								visible: false,
							});
							that.fetch('');
						})
					} else {
						json = Object.assign({}, json, { rate: parseInt(values.rate), endTime: values.endTime, startTime: values.startTime, taskType: parseInt(values.taskType), methodName: typeData.methodName, groupName: typeData.groupName, className: typeData.className })
						jiek(json).then(data => {
							if (data.data.code === 200) {
								openNotification('success', '操作成功')
							} else {
								openNotification('warning', data.data.msg)
							}
							const that = this;
							that.handleCancel();
							that.props.form.resetFields();
							that.setState({
								visible: false,
							});
							that.fetch('');
						})
					}
				}
				//新增 修改接口封装
				if (this.state.handleType === 0) {
					choose(APIService.addJob);
				} else {
					choose(APIService.updateJob);
				}
			}
		})
	}

	//弹出删除框
	deleteJob = (data, type) => {
		const that = this;
		confirm({
			title: '确认删除' + '[' + data.name + ']?',
			okText: '确认',
			okType: 'warning',
			cancelText: '取消',
			onOk() {
				if (type === 2) {
					APIService.deleteJob(data.id).then(data => {
						if (data.data.code === 200) {
							openNotification('success', '删除成功');
						} else {
							openNotification('warning', data.data.msg)
						}
						that.fetch('')
					}).catch(function (error) {
						openNotification('error', error.message);
					});
				}
			},
			onCancel() {
				console.log('Cancel');
			},
		});
	}

	onExpand = (record, index, indent, expanded) => { }

	//  1修改
	showModal = (data, type) => {
		const that = this;
		if (type === 1) {
			this.props.form.setFieldsValue({
				id: data.id,
				groupName: data.groupName,
				className: data.className,
				methodName: data.methodName,
				explain: data.explain,
				jobCod: data.jobCod,
				name: data.name,
				rate: data.rate,
				taskType: data.taskType,
				typeData: data.typeData
			})
			this.setState({
				startTime: data.startTime,
				endTime: data.endTime,
				time: data.startTime,
			})
		}else{
			this.setState({
				startTime:moment().startOf('day').format('YYYY-MM-DD HH:mm:ss'),
				endTime: data.endTime,
				time: moment().startOf('day').format('YYYY-MM-DD HH:mm:ss'),
			})	
		}

		this.setState({
			visible: true,
			modalData: data,
			handleType: type,
			className: data.className,
			methodName: data.methodName,
			groupName: data.groupName,
			id: data.id,
		})
		console.log(this.state.startTime)
	};

	//新增按钮取消
	handleCancel = e => {
		this.props.form.resetFields();
		this.setState({
			visible: false,
		});
	};

	//查询按钮
	handleSearch = (e) => {
		this.props.form.validateFields(['datename', 'groupName'], (err, values) => {
			var str = '?';
			console.log(values)
			if (values.datename !== undefined) {
				str += 'name=' + values.datename + '&';
			}
			if (values.groupName !== undefined) {
				str += 'groupName=' + values.groupName + '&';
			}
			this.fetch(str);
		});
	};

	//选择器菜单
	handleChange = (value) => {
		console.log(`selected ${value}`);
	}

	//抽屉
	showDrawer = () => {
		this.setState({
			visible: true,
		});
	};
	onClose = () => {
		this.setState({
			visible: false,
		});
		this.props.form.resetFields();
	};

	//时间选择框
	range = (start, end) => {
		const result = [];
		for (let i = start; i < end; i++) {
			result.push(i);
		}
		return result;
	}

	//单选框
	radioChange = e => {
		console.log('radio checked', e.target.value);
		this.setState({
			value: e.target.value,
		});
	};

	//显示隐藏
	planTypeOnchage = (value) => {
		this.setState({
			visible_planType: value
		})

	}



	render() {
		const { getFieldDecorator } = this.props.form;
		const config = {
			initialValue: moment(this.state.startTime, 'YYYY-MM-DD HH:mm:ss'),
			rules: [{ type: 'object', message: '请选择日期' }],
		};
		const config2 = {
			initialValue: this.state.endTime ? moment(this.state.endTime, 'YYYY-MM-DD HH:mm:ss') : '',
			rules: [{ type: 'object', message: '请选择日期' }],
		};
		const config3 = {
			initialValue: moment(this.state.time, 'YYYY-MM-DD HH:mm:ss'),
			rules: [{ type: 'object', message: '请选择日期' }],
		};
		var operations = <div className="mydiv" > <Button icon="plus" onClick={() => this.showModal([], 0)} type="primary" > 新增 </Button></div >
		return (
			<div className="shadow-radius">
				<Form className="search-form" style={{ paddingBottom: 0 }}>
					<Row gutter={24}>
						<Col span={4}>
							<FormItem label="周期计划名称">
								{getFieldDecorator('datename')(
									<Input placeholder='请输入周期计划名称' />
								)}
							</FormItem>
						</Col>
						<Col span={4}>
							<FormItem label="周期计划分组">
								{getFieldDecorator('groupName')(
									<Select style={{ width: 160 }} onChange={this.handleChange}>
										{this.state.typeData.map(data => <Option key={JSON.stringify(data)} value={data.groupName}>{data.groupName}</Option>)}
									</Select>
								)}
							</FormItem>
						</Col>
						<Col span={2} style={{ marginRight: '10px', display: 'flex' }} className="serarch-btns">
							<FormItem>
								<Button icon="search" type="primary" htmlType="submit" className={'btn'} onClick={this.handleSearch}>
									查询
								</Button>
							</FormItem>

						</Col>
					</Row>
				</Form>
				<Tabs tabBarExtraContent={operations} onChange={this.handleChangeTab} >
					<TabPane tab={<span><Icon type="table" /><strong>周期列表</strong> </span>} key="1">

						<Table columns={this.state.columns} dataSource={this.state.dataSource} pagination={this.state.pagination} loading={this.state.loading} onExpand={(expanded, record) => this.onExpand(expanded, record)} rowKey={record => record.id} />
					</TabPane>
				</Tabs>

				{/* 抽屉 */}
				<Drawer
					title="新增周期计划"
					width={720}
					onClose={this.onClose}
					ok={this.submitAdd}
					visible={this.state.visible}
					bodyStyle={{ paddingBottom: 80 }}
				>
					<div>
						<Form layout="vertical" >
							<Row gutter={16}>
								<Col span={12}>
									<Form.Item label="编码">
										{getFieldDecorator('jobCod', {})(<Input placeholder='请输入编码' />)}
									</Form.Item>
								</Col>
								<Col span={12}>
									<Form.Item label="周期计划名称">
										{getFieldDecorator('name', {})(<Input placeholder='请输入周期计划名称' />)}
									</Form.Item>
								</Col>
							</Row>
							<Row gutter={16}>
								<Col span={12}>
									<Form.Item label="周期计划分组">
										{getFieldDecorator('groupName', {})(
											<Select placeholder="请选择周期计划分组">
												{this.state.typeData.map(data => <Option key={JSON.stringify(data)} value={data.groupName}>{data.groupName}</Option>)}
											</Select>
										)}
									</Form.Item>
								</Col>
								<Col span={12}>
									<Form.Item label="周期计划类型">
										{getFieldDecorator('taskType')(
											<Select placeholder="请选择周期计划类型" onChange={(e) => this.planTypeOnchage(e)}>
												<Option value="0">执行一次</Option>
												<Option value="1">基础循环</Option>
											</Select>
										)}
									</Form.Item>
								</Col>
							</Row>
						</Form>
					</div>


					<div style={{ display: this.state.visible_planType === '0' ? 'block' : 'none' }} >
						<div className="ant-divider ant-divider-horizontal ant-divider-with-text-left" role="separator">
							<span className="ant-divider-inner-text"> <b>执行一次</b> </span>
						</div>
						<div
							title="新增周期计划"
							width={720}
							onClose={this.onClose}
							visible={this.state.visible}
						>
							<Form layout="vertical">
								<Row gutter={16}>
									<Col span={12}>
										<Form.Item label="时间日期">
											{getFieldDecorator('time', config3)(
												<DatePicker
													locale={locale}
													format="YYYY-MM-DD HH:mm:ss"
												/>
											)}
										</Form.Item>
									</Col>
								</Row>
								<Row gutter={16}>
									<Col span={24}>
										<Form.Item label="说明">
											{getFieldDecorator('explain')
												(<Input.TextArea rows={4} placeholder="请输入说明" />)}
										</Form.Item>
									</Col>
								</Row>
							</Form>
						</div>
					</div>

					<div style={{ display: this.state.visible_planType === '1' ? 'block' : 'none' }}>
						<div className="ant-col ant-col-24" >
							<div className="ant-divider ant-divider-horizontal ant-divider-with-text-left" role="separator">
								<span className="ant-divider-inner-text">频率 </span>
							</div>

							<div>
								<Form layout="inline">
									<Form.Item>
										每: <Input style={{ width: 200 }} />
									</Form.Item>
									<Form.Item>
										{getFieldDecorator('rate')(
											<Select style={{ width: 220 }}>
												<Option value="2">小时</Option>
												<Option value="3">天</Option>
												<Option value="4">周</Option>
											</Select>
										)}
									</Form.Item>
								</Form>
							</div>
						</div>

						<div className="ant-col ant-col-24">
							<div className="ant-divider ant-divider-horizontal ant-divider-with-text-left" role="separator">
								<span className="ant-divider-inner-text">持续时间 </span>
							</div>
							<div>
								<Form>
									<FormItem>
										开始日期:
								{getFieldDecorator('startTime', config)(
										<DatePicker
											locale={locale}
											format="YYYY-MM-DD HH:mm:ss"
										//defaultValue={moment(this.state.startTime, 'YYYY-MM-DD HH:mm:ss')}
										/>
									)}
									</FormItem>
								</Form>
								<Form>
									<FormItem>
										<Radio.Group onChange={this.radioChange} value={this.state.value}>
											<Radio value={1}>结束日期</Radio>
											<Radio value={2}>无结束日期</Radio>
										</Radio.Group>
									</FormItem>

									<FormItem>
										结束日期:
								{getFieldDecorator('endTime', config2)(
										<DatePicker
											locale={locale}
											format="YYYY-MM-DD HH:mm:ss"
										//defaultValue={moment(this.state.endTime, 'YYYY-MM-DD HH:mm:ss')}
										/>
									)}
									</FormItem>
									<FormItem>
										说明：{getFieldDecorator('explain')
											(<Input.TextArea rows={4} placeholder="请输入说明" style={{ width: 380 }} />)}
									</FormItem>
								</Form>

							</div>
						</div>
					</div>
					<div
						style={{
							position: 'absolute',
							right: 0,
							bottom: 0,
							width: '100%',
							borderTop: '1px solid #e9e9e9',
							padding: '10px 16px',
							background: '#fff',
							textAlign: 'right',
						}}
					>
						<Button onClick={this.onClose} style={{ marginRight: 8 }}>
							取消
            </Button>
						<Button type="primary" onClick={this.submitAdd}>
							保存
            </Button>
					</div>
				</Drawer>

			</div>
		)
	}
}

export default Form.create()(App);